package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * 1034. 边框着色
 *
 * @Author liw
 * @Date 2021/8/10 22:10
 * @Version 1.0
 */
public class ColorBorder {

    public static void main(String[] args) {
        ColorBorder test = new ColorBorder();

//        int[][] arr = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
//        int row = 1;
//        int col = 1;
//        int color = 3;

//        int[][] arr = {{1, 1}, {1, 2}};
//        int row = 0;
//        int col = 0;
//        int color = 3;

        //[[1,1,1,1,1,2],[1,2,1,1,1,2],[1,1,1,1,1,2]]
        int[][] arr = {{1,2,1,2,1,2}, {2,2,2,2,1,2}, {1,2,2,2,1,2}};
        int row = 1;
        int col = 3;
        int color = 1;
        int[][] ints = test.colorBorder(arr, row, col, color);
        for (int[] anInt : ints) {
            System.out.println(Arrays.toString(anInt));
        }
    }

    private int m;
    private int n;
    private int value;
    private int[][] grid;
    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        this.value = grid[row][col];
        if (value == color) {
            return grid;
        }
        m = grid.length;
        n = grid[0].length;
        this.grid = grid;
        find(row, col);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1001 && (i == 0 || i == m - 1 || j == 0 || j == n - 1
                        || grid[i + 1][j] <= 1000 || grid[i - 1][j] <= 1000
                        || grid[i][j + 1] <= 1000 || grid[i][j - 1] <= 1000)) {
                    grid[i][j] = 1002;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1002) {
                    grid[i][j] = color;
                } else if (grid[i][j] == 1001) {
                    grid[i][j] = value;
                }
            }
        }
        return grid;
    }

    public void find(int row, int col) {
        if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] != value) {
            return;
        }
        grid[row][col] = 1001;
        find(row + 1, col);
        find(row - 1, col);
        find(row, col - 1);
        find(row, col + 1);
    }

}
